<template lang="html">
  <div class="detail">
    <team-header :title="gameTitle"></team-header>
    <!-- <img
      class="plq"
      src="../../assets/images/pinglunqu.png" alt="" v-if="gameStep!==0" > -->
    <div class="group_con" :style='{backgroundImage: winBg}'>
      <div class="con_top">
        <div class="group_name">
          {{ teamDetail.GAME_NAME }}
        </div>

        <div class="group_earnings" v-if="gameStep === 3 || gameStep === 4">
          <p>{{teamDetail.TOTAL_PROFIT|toFix(2)}}</p>
          <p>团队累计平均收益率</p>
          <p>更新时间：6.1 15:01</p>
        </div>

        <div class="countdown" v-else>
            <div v-text="gameStep === 0 ? '报名倒计时': '开赛倒计时'"></div>
            <div class="time">
              <template v-if="showDay">
                <span class="leaveDays">距开赛还有{{days}}天</span>
              </template>
              <template v-else>
                <span>{{hours}}</span>
                <span>{{minute}}</span>
                <span>{{second}}</span>
              </template>
            </div>
        </div>

      </div>
      <div class="con_bot">
        <div class="group_detail">
          <template v-for="(item,index) in teamInfo">
            <div class="detail_list">
              <img :src="teamInfoBg(index)" alt="">
              <div >
                <p>{{item[0]}}</p>
                <p>{{item[1]}}</p>
              </div>
            </div>

          </template>
        </div>
      </div>

    </div>

    <div class="applied" v-if="gameStep === 3 ">
      <div class="myRank" v-if="isAttend">
        <div class="myRank_con">
          <p>已报名</p>
          <span>我的排名: {{rank}}</span>
        </div>
        <span class="back_ground" @click='goBack'>
          回广场
          <i class="iconfont ">&#xe62e;</i>
        </span>
      </div>
      <div class="dealAndStock" v-if="isAttend">
        <!-- <div :class="{'game_over': gameStep === 4, 'gaming':  gameStep === 3 }" v-text="gameStep === 4 ? '比赛结束': '比赛交易'">
          比赛交易
        </div> -->
        <div class="gaming" @click="gotoTrade">
          比赛交易
        </div>
        <div class="stock" @click="gotoStock">
          查比赛持仓
        </div>
      </div>
    </div>
    <!-- <p class='sign_up' v-if = "gameStep === 0 || gameStep === 1 || gameStep === 2" v-text="gameStep !== 0 ? gameStep === 1 ? '报名中' : '未开赛': '报名该队' "></p> -->
    <p 
      :class="[{'end': gameStep === 4 || gameStep === 0}, 'sign_up']"  
      v-text="buttonText(gameStep)"  
      v-if="!isAttend"
      @click="attendGame"></p>

    <new-comment v-if="gameStep ===3 || gameStep ===4" />
    <div class="tab_wrap">
      <div class="tab">
        <span @click="showAllList">总榜单</span>
        <span @click="showWeekList">周榜单</span>
        <div class="tab_background" ref='tabBC'></div>
      </div>
    </div>
    <group-list
      ref="grouplist"
      :gameStep="gameStep"
      :isLoading="isRankLoading"
      :showTotal="showTotal"
      :rankList="rankList"
      :gameDetail="teamDetail"
      :isAttend="isAttend"
      v-on:loadmore="showMoreList"/>

    <game-pwd-input-modal v-on:success="registerSuccess"/>
    <!-- <div class="chat-bottom-wrap" ref='chat' v-show='allowChat'>
      <speak ref='speak' @speaking='append2Msgs' :options='entryData' @emojiVisible='onEmojiVisible'/>
    </div> -->
  </div>
</template>

<script>
import TeamHeader from './TeamHeader'
// import Speak from 'components/game/comment/Speak'
import GroupList from './GroupList'
import NewComment from './children/NewComment'
import GamePwdInputModal from  'components/modal/GamePwdInputModal'
import RemoteDAO from 'common/remoteDAO'

let timer
const apiAddress = 'http://10.176.118.55:1038/gt/nrng'
const pageSize = 20

export default {
  name: 'detail',
  data () {
    return {
      teamInfo: [["已参赛人数", "--"], ["人气值","--"], ["空仓率","--"]],
      gameId: this.$route.query.gameId || '',
      gameTitle: this.$route.query.gameTitle || '',
      showTotal: true,
      totalPageNum: 1,
      weekPageNum: 1,
      rankList: [],
      myRankInfo: {},
      isAttend: false,
      isRankLoading: false,
      gameStep: 0,
      showDay: false,
      hours: '--',
      minute: '--',
      second: '--',
      days: '--',
      rank: 121
    }

  },
  components: {
    TeamHeader,
    GroupList,
    GamePwdInputModal,
    NewComment
  },
  created () {
    // this.gameStep = 4
    this.gameStep = Number(this.teamDetail.GAME_STEP)
    this.teamInfo[0][1] = this.teamDetail.GAME_ATTEND_PERSON+'人'
    this.teamInfo[1][1] = this.teamDetail.GAME_ATTEND_PERSON+'次'
    this.teamInfo[2][1] = this.teamDetail.GAME_ATTEND_PERSON+'%'
  },
  mounted () {
    if (this.gameStep !== 3 && this.gameStep !== 4){
      let timer = setInterval(() => {
        this.showTime()
      },200)
      this.teamInfo = this.teamInfo.slice(0,2)
    }
    this.initRankList()
    this.getMyRank()
    this.checkIfSign()
  },
  filters: {
    toFix (val,length) {
      return Number(val).toFixed(length)+'%'
    }
  },
  methods: {
    teamInfoBg (index) {
      let teamInfoBg
      (teamInfoBg = index === 0 && `${require('assets/images/team/people@2x.png')}`) ||
      (teamInfoBg = index === 1 && `${require('assets/images/team/renqi@2x.png')}`) ||
      (teamInfoBg = index === 2 && `${require('assets/images/team/kongcang@2x.png')}`)
      return teamInfoBg
    },
    attendGame () {
      if (this.gameStep !== 3) return

      if (this.teamDetail.IS_GAMEPWD === '1'){
        this.$store.dispatch('setModal', { visible: true, modalId: 'gamePwdInputModal',gameId:this.gameId, createUser:this.teamDetail.CREATE_USER });
      } else {
        RemoteDAO.callUC12008304(
          localStorage.getItem('userCode'),
          this.gameId,
          '',
          this.teamDetail.CREATE_USER, resp => {
            if (resp.error === '0') {
              this.$store.dispatch('setTip', { text: '参赛成功！' })
              this.checkIfSign()
            } else {
              this.$store.dispatch('setTip', { text: resp.data })
            }
          })
      }
    },
    registerSuccess () {
      this.$store.dispatch('setTip', { text: '参赛成功' })
      this.$store.dispatch('setModal', { visible: false, moduleId: 'gamePwdInputModal' })
      this.checkIfSign()
    },
    gotoTrade () {
      this.$router.push({ path: '/trade/buyin', query: {
        gameId: this.gameId
      }})
    },
    gotoStock () {
      this.$router.push({ path: '/trade/stock', query: {
        gameId: this.gameId
      }})
    },
    initRankList () {
      setTimeout(() => {
        if (this.rankList.length === 0) {
          this.totalPageNum = 1
          RemoteDAO.callHB003(localStorage.getItem('userCode'), this.gameId,
            pageSize, 1, 0, res => {
            this.totalPageNum = 2
            this.rankList = res.data.body
            if (res.data.body.length < pageSize) {
              this.$refs.grouplist.bottomAllLoaded()
            }
          })
        }
      },100)
    },
    showAllList () {
      this.$refs.tabBC.style.transform = 'translate3d(0, 0, 0)'
      this.totalPageNum = 1
      if (!this.showTotal) {
        this.isRankLoading = true
        this.showTotal = true
        this.$refs.grouplist.resetLoadMore()
        RemoteDAO.callHB003(localStorage.getItem('userCode'), this.gameId,
          pageSize, 1, 0, res => {
          this.totalPageNum = 2
          this.rankList = res.data.body
          this.isRankLoading = false
          if (res.data.body.length < pageSize) {
            this.$refs.grouplist.bottomAllLoaded()
          }
        })
      }
    },
    showWeekList () {
      clearTimeout(timer)
      this.$refs.tabBC.style.transform = 'translate3d(100%, 0, 0)'
      this.weekPageNum = 1
      if (this.showTotal) {
        this.isRankLoading = true
        this.showTotal = false
        this.$refs.grouplist.resetLoadMore()
        $.ajax({
          method: 'GET',
          url: `${apiAddress}/getNrngSubteamUserList/${this.gameId}/1/${pageSize}`,
          dataType: 'JSONP',
          jsonpCallback: 'success',
          success: resp => {
            console.info('week rank', resp.data.teamUserList)
            this.weekPageNum = this.weekPageNum + 1
            this.rankList = resp.data.teamUserList
              .map(item => JSON.parse(item))
            this.isRankLoading = false
            if (resp.data.teamUserList.length < pageSize) {
              this.$refs.grouplist.bottomAllLoaded()
            }
          }
        })
      }
    },
    showMoreList () {
      console.log('show more rank data')
      if (this.showTotal) {
        RemoteDAO.callHB003('', this.gameId,
          pageSize, this.totalPageNum, 0, res => {
            // 防止数据重复
            for (let i = 0;i < this.rankList.length; i++) {
              if (!!res.data.body.find(item => 
                item.USER_CODE === this.rankList[i].USER_CODE)) {
                return false
              }
            }
            this.totalPageNum = this.totalPageNum + 1
            this.rankList = this.rankList.concat(res.data.body)
            if (res.data.body.length < pageSize) {
              this.$refs.grouplist.bottomAllLoaded()
            } else {
              this.$refs.grouplist.bottomLoaded()
            }
          })
      } else {
        $.ajax({
          method: 'GET',
          url: `${apiAddress}/getNrngSubteamUserList/
            ${this.gameId}/${this.weekPageNum}/${pageSize}`,
          dataType: 'JSONP',
          jsonpCallback: 'success',
          success: resp => {
            console.info('week rank', resp.data.teamUserList)
            this.weekPageNum = this.weekPageNum + 1
            this.rankList = this.rankList.concat(resp.data.teamUserList
              .map(item => JSON.parse(item)))
            if (resp.data.teamUserList.length < pageSize) {
              this.$refs.grouplist.bottomAllLoaded()
            } else {
              this.$refs.grouplist.bottomLoaded()
            }
          }
        })
      }
    },
    getMyRank () {
      RemoteDAO.callJCL11143(
        localStorage.getItem('userCode'),
        this.gameId, resp => {
          if (resp.error === '0') {
            this.myRankInfo = resp.data.body
          }
        })
    },
    checkIfSign () {
      RemoteDAO.callUC12008303({
        userCode: localStorage.getItem('userCode'),
        actionFlag: 1,
        pageSize: 1,
        pageNo: 1,
        gameID: this.gameId
      }, resp => {
        // 是否参加了比赛
        this.isAttend = resp.data.body.length > 0
      })
    },
    showTime () {
      let time = new Date('2017-09-22').getTime() - new Date().getTime()
      this.days = Math.floor(time / (24*3600*1000))
      if (this.days > 1) {
        this.showDay = true
      } else {
        let leave1 = time % (24*3600*1000)    //计算天数后剩余的毫秒数
        this.hours = this.fmt(Math.floor(leave1/(3600*1000)))
        let leave2 = leave1 % (3600*1000)        //计算小时数后剩余的毫秒数
        this.minute = this.fmt(Math.floor(leave2/(60*1000)))
        let leave3 = leave2 % (60*1000)      //计算分钟数后剩余的毫秒数
        this.second = this.fmt(Math.round(leave3/1000))
      }
    },
    fmt (date) {
      let fmtDate;
      (date.toString().length == 1 && (fmtDate = '0'+date)) || (fmtDate = date)
      return fmtDate
    },
    goBack () {

    },
    buttonText (gameStep) {
      switch (gameStep) {
        case 0: return '比赛未开始'
        case 1: return '报名中'
        case 2: return '未开赛'
        case 3: return '报名该队'
        case 4: return '比赛结束'
        default: return
      }
    }
  },
  computed: {
    winBg () {
      if (this.gameStep === 4) {
        return `url(${require('assets/images/team/winwin@2x.png')})`
      }else {
        return
      }
    },
    teamDetail () {
      const { gameId = '' } = this.$route.query
      console.log('teamDetail', this.$store.state.team.teamList
        .filter(t => t.GAME_ID === gameId)[0])
      return this.$store.state.team.teamList
        .filter(t => t.GAME_ID === gameId)[0]
    },
    gameDetail () {

    }

  },
  destoryed () {
    clearInterval(timer)
  }
}
</script>

<style lang="less" scoped>
.flexLayout(@justify-content:center,@align-items:center){
  display: flex;
  justify-content: @justify-content;
  align-items: @align-items;
}
.ellipsis(@-webkit-line-clamp:1) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: @-webkit-line-clamp;
  -webkit-box-orient: vertical;
}


.detail {
  position: relative;
  background-color: #F7743A;
  .plq {
    position: fixed;
    right: 10px;
    bottom: 50px;
    z-index: 1;
  }
}
.countdown {
  text-align: center;
  margin-bottom: 6px;
  .time {
    width: 100%;
    margin-top: 6px;
    span {
      color: #FFF782;
      background-color: #98381E;
      border-radius: 5px;
      padding: 2px;
      font-size: 18px;
    }
    span.leaveDays {
      font-size: 14px;
      padding: 0 4px;
    }
    span:nth-child(2) {
      position: relative;
      margin: 0 5px;
      &::before, &::after{
        content: ':';
        position: absolute;
        top: 5%;
        font-weight: 900;
        color: #98381E;
      }
      &::before {
        left: -6px;
      }
      &::after {
        right: -6px;
      }
    }
  }
}

.sign_up {
  color: #A33815;
  background-color: #FFF005;
  width: 223px;
  border-radius: 19px;
  text-align: center;
  margin: 0 auto 20px;
  padding: 8px 0;
  font-size: 16px;
  font-weight: 900;
}
.end {
  color: #BFBFBF;
  background-color: #6D6D6D;
}
.applied {
  width: 100%;
}
.myRank {
  position: relative;
  height: 47px;
  background-image: repeating-linear-gradient(-50deg, #EE6C33, #EE6C33 12px,#F7743A 0, #F7743A 24px);
  .back_ground {
    position: absolute;
    top: 13px;
    right: 20px;
    padding:0 6px 0 10px;
    background-color: #E65222;
    border-radius: 11px;
    border: 1px solid #fff;
    color: #FFFCFA;
    i {
      font-size: 14px;
    }
  }
}
.myRank_con {
  position: absolute;
  margin-left: 50%;
  transform: translateX(-40%);
  height: 100%;
  p {
    margin-bottom: -4px;
    color: #FFE867;
    font-size: 20px;
    line-height: 32px;
  }
  span {
    color: #67220C;
    font-size: 12px;
  }
  &::before {
    content: '';
    position: absolute;
    background-image: url('../../assets/images/team/gou@2x.png');
    background-size: 100%;
    left: -42px;
    top: 5px;
    width: 38px;
    height: 38px;
  }
}
.dealAndStock {
  width: 90%;
  margin: 0 auto;
  padding: 4px;
  background-color: #E15F25;
  border-radius: 15px;
  font-size: 16px;
  font-weight: 900;
  margin-top: 20px;
  margin-bottom: 20px;
  .flexLayout(space-between);
  .gaming {
    width: 48%;
    background-color: #FFF005;
    color: #A33815;
    height: 38px;
    .flexLayout();
    border-radius: 10px;
  }
  // .game_over {
  //   width: 48%;
  //   background-color: #6D6D6D;
  //   color: #BFBFBF;
  //   height: 38px;
  //   .flexLayout();
  //   border-radius: 10px;
  // }
  .stock {
    width: 48%;
    height: 38px;
    background-color: #fff;
    color: #938CAC;
    .flexLayout();
    border-radius: 10px;
  }
}
.group_con {
  padding: 11px 20px 20px 16px;
  color: #fff;
  background-repeat: no-repeat;
  background-position: 35% top;
  background-size: 200px 100px;
}
.con_top {
  .flexLayout(space-between);
  position: relative;
  .group_name {
    width: 40%;
    font-size: 21px;
    text-align: left;
    font-weight: 900;
    // .flexLayout(flex-start);
    .ellipsis(1);
  }
  .group_earnings {
    text-align: center;
    width: 40%;
    p:nth-of-type(1) {
      width: 90%;
      margin:0 auto 5px;
      background-color: #fff;
      color: #FF3333;
      font-size: 20px;
      font-weight: 900;
      border-radius: 13px;
    }
    p:nth-of-type(2){
      margin: 0;
      font-size: 12px;
    }
    p:nth-of-type(3) {
      font-size: 12px;
      transform: scale(0.9);
      color: #FFF7C3;
    }
  }
  &::before {
    content:'';
    position: absolute;
    bottom: 0;
    left: 0;
    height: 1px; /*no*/
    width: 100%;
    background-image: linear-gradient(to right, transparent 50%, rgb(200,200,200) 0);
    background-size: 5px 100%; /*no*/
  }
}
.con_bot {
  padding-top: 20px;
}
.group_detail {
  .flexLayout(space-around);
}
.detail_list {
  .flexLayout(center);
  flex-basis: 33.33%;
  div {
    margin-left: 4px;
    p:nth-of-type(1){
      // font-size: 12px;
      margin-bottom: 0;
      @media screen {
        @media (max-width: 400px) {
          font-size: 12px;/*no*/
        }
        @media (min-width: 400px) {
          font-size: 14px;/*no*/
        }
      }
    }
    p:nth-of-type(2){
      // font-size: 14px;
      // font-weight: 900;
      margin: 0;
      .ellipsis(1);
      @media screen {
        @media (max-width: 400px) {
          font-size: 14px;/*no*/
          line-height: 22px;
        }
        @media (min-width: 400px) {
          font-size: 16px;/*no*/
          line-height: 24px;
        }
      }
    }
  }
  img {
    width: 27px;
    height: 27px;
  }
}
.tab_wrap {
  width: 100%;
  height: 69px;
  box-sizing: border-box;
  padding: 17px 38px 22px 38px;
  background: #fff;
}

.tab {
  width: 100%;
  height: 100%;
  color: #fff;
  background-color: #926969;
  text-align: center;
  border-radius: 16px;
  font-size: 12px;
  position: relative;
  span {
    position: absolute;
    z-index: 10;
    width: 50%;
    height: 100%;
    left: 0;
    top: 0;
    .flexLayout();
    background-color: transparent;
  }
  span:nth-child(2) {
    left: 50%;
  }
}
.tab_background {
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 16px;
  background-color: #F7743A;
  width: 50%;
  height: 100%;
  transition: all 0.3s ease;
  &::before {
    position: absolute;
    bottom: -8px;
    left: 45%;
    content: '';
    width: 0;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-top: 8px solid #F7743A;
  }
}
// .chat-bottom-wrap{
//   position: fixed;
//   bottom: 0;
//   width: 100%;
//   background: #fff;
//   border-radius: 5px;
// }

</style>
